package com.crx.springbootinit.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

public class JwtHelper {
    private static long tokenExpiration=365*24*60*60*1000;
    private static String tokenSignKey="123456";

    public static String createToken(Long userId,String userName,String role){
        String token= Jwts.builder()
                //分类
                .setSubject("AUTH-USER")
                //设置时长
                .setExpiration(new Date(System.currentTimeMillis()+tokenExpiration))
                //设置主体
                .claim("userId",userId)
                .claim("userName",userName)
                .claim("role",role)
                //签名部分
                .signWith(SignatureAlgorithm.HS512,tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    public static Long getUserId(String token){
        try {
            if (StringUtils.isEmpty(token)) {
                return null;
            }
            Jws<Claims> claimsJws= Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims=claimsJws.getBody();
            Integer userId= (Integer) claims.get("userId");
            return userId.longValue();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static String getUserName(String token){
        try {
            if (StringUtils.isEmpty(token)) {
                return "";
            }
            Jws<Claims> claimsJws= Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims=claimsJws.getBody();
            String userName= (String) claims.get("userName");
            return userName;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static String getRole(String token){
        try {
            if (StringUtils.isEmpty(token)) {
                return "";
            }
            Jws<Claims> claimsJws= Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims=claimsJws.getBody();
            String role= (String) claims.get("role");
            return role;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}